package com.myutils;

import java.util.ResourceBundle;

import org.apache.log4j.helpers.LogLog;

/**
 * @author Lan
 */
public class PropUtil {
	static String DELIM_START = "${";
	static char DELIM_STOP = '}';
	static int DELIM_START_LEN = 2;
	static int DELIM_STOP_LEN = 1;

	private static ResourceBundle bundle = null;

	private PropUtil() {
	}

	static {
		load("config");
	}

	public static void load(String propFileName) {
		bundle = ResourceBundle.getBundle(propFileName);
	}

	public static String getStrValue(String key) {
		String value = bundle.getString(key);
		return substVars(value, bundle);
	}

	public static int getIntValue(String key) {
		return Integer.parseInt(getStrValue(key));
	}

	public static String substVars(String val, ResourceBundle bundle)
			throws IllegalArgumentException {

		StringBuffer sbuf = new StringBuffer();

		int i = 0;
		int j, k;

		while (true) {
			j = val.indexOf(DELIM_START, i);
			if (j == -1) {
				// no more variables
				if (i == 0) { // this is a simple string
					return val;
				} else { // add the tail string which contails no variables
					// and return the result.
					sbuf.append(val.substring(i, val.length()));
					return sbuf.toString();
				}
			} else {
				sbuf.append(val.substring(i, j));
				k = val.indexOf(DELIM_STOP, j);
				if (k == -1) {
					throw new IllegalArgumentException(
							'"'
									+ val
									+ "\" has no closing brace. Opening brace at position "
									+ j + '.');
				} else {
					j += DELIM_START_LEN;
					String key = val.substring(j, k);
					// first try in System properties
					String replacement = getSystemProperty(key);
					// then try props parameter
					if (replacement == null && bundle != null) {
						replacement = bundle.getString(key);
					}

					if (replacement != null) {
						// Do variable substitution on the replacement string
						// such that we can solve "Hello ${x2}" as "Hello p1"
						// the where the properties are
						// x1=p1
						// x2=${x1}
						String recursiveReplacement = substVars(replacement,
								bundle);
						sbuf.append(recursiveReplacement);
					}
					i = k + DELIM_STOP_LEN;
				}
			}
		}
	}

	public static String getSystemProperty(String key) {
		String value = null;
		try {
			value = System.getProperty(key);
		} catch (Throwable e) { // MS-Java throws
								// com.ms.security.SecurityExceptionEx
			LogLog.debug("Was not allowed to read system property \"" + key + "\".");
		}
		return value;
	}
}
